using System.Collections.Generic;
using System.Linq;

namespace Flood.FloodStrategies
{
	/// <summary>
	/// moves on the sample set
	/// 22859 in 2.409 w/count > 2
	/// 22870 in 2.435 w/count > 3
	/// 22886 in 2.414 w/count > 4
	/// </summary>
	public sealed class FloodAdjacentColorThatHasTheMostDrySquaresPreferLargerShapes : FloodStrategyBase, IFloodStrategy
	{
		#region IFloodStrategy Members

		public Result GetNextToFlood(IEnumerable<Shape> moistShapes, Grid grid)
		{
			var dryAdjacent = moistShapes
				.Select(shape => new { Count = CountDryAdjacentSquares(shape), Shape = shape })
				.OrderByDescending(item => item.Count);
			var first = dryAdjacent.First();
			if (first.Count == 0)
			{
				// there are no more blocked squares so the solution
				// order for the remaining squares doesn't matter
				return new Result(moistShapes.Select(shape => shape.Color).OrderByDescending(x => x).ToList(), true);
			}
			char bestColor = first.Shape.Color;
			var next = dryAdjacent.Skip(1).FirstOrDefault();
			if (next != null)
			{
				int adjacentableShapesWithBestColor =
					next.Shape.DryAdjacentShapes
						.Where(shape => shape.Color == bestColor)
						.Count();
				if (adjacentableShapesWithBestColor > 2)
				{
					bestColor = next.Shape.Color;
				}
			}

			return new Result(bestColor, false);
		}

		#endregion
	}
}